import { json, type ActionFunctionArgs } from "@remix-run/node";

// Debug-only endpoint to exchange OAuth code for an admin access token.
// Inputs (JSON body): { shop: string, code: string, redirectUri?: string }
// NEVER expose this in production without proper safeguards.
export const action = async ({ request }: ActionFunctionArgs) => {
  try {
    if (request.method !== "POST") {
      return json({ success: false, error: "Method not allowed" }, { status: 405 });
    }

    const { shop, code, redirectUri } = await request.json();

    if (!shop || !code) {
      return json({ success: false, error: "Missing shop or code" }, { status: 400 });
    }

    const client_id = process.env.SHOPIFY_API_KEY;
    const client_secret = process.env.SHOPIFY_API_SECRET;

    if (!client_id || !client_secret) {
      return json({ success: false, error: "Shopify app credentials not configured" }, { status: 500 });
    }

    const tokenUrl = `https://${shop}/admin/oauth/access_token`;

    const response = await fetch(tokenUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        client_id,
        client_secret,
        code,
        ...(redirectUri ? { redirect_uri: redirectUri } : {}),
      }),
    });

    const data = await response.json();

    if (!response.ok) {
      return json(
        {
          success: false,
          error: data?.error || "Failed to exchange code",
          details: data,
        },
        { status: response.status }
      );
    }

    // data: { access_token, scope, ... }
    return json({ success: true, data });
  } catch (error: any) {
    return json({ success: false, error: error?.message || "Unexpected error" }, { status: 500 });
  }
};

export const loader = async () => {
  return json({ success: false, error: "Use POST" }, { status: 405 });
};


